<?php


namespace app\admin\model;
use think\facade\Cookie;
use think\facade\Session;
use think\Model;

class AdminUser extends Model
{
    const LOGIN_NAME = 'user_info';
    protected $connection = 'mysql';
    /**
     * @param string $u 用户名
     * @param string $p 密码
     * @return bool 是否登录成功
     * @throws
     */
    public function login(string $u,string $p,$isRemmber=false):bool {
        $user = self::where('username',$u)->find();
        $user || error('用户名不存在!');
        if(self::encrypt($p) !== $user->password) error('密码错误');
        Session::set(self::LOGIN_NAME,$user->getData());
        if($isRemmber) {
            Cookie::set('username', $u, 3600*24*7);
            Cookie::set('password', self::encrypt($p), 3600*24*7);
        }
        return true;
    }

    /**
     * 返回是否已经登陆
     * @return bool true 已经登陆
     */
    public static function hasLogin() : bool {
        if(!Session::has(self::LOGIN_NAME)) return false;
        return Session::get(self::LOGIN_NAME) !== null;
    }

    /**
     * 返回是否记住密码
     * @throws
     * @return bool
     */
    public static function loginRemember():bool{
        $username = Cookie::get('username');
        $password = Cookie::get('password');
        if($username && $password) {
            $user = self::where('username',$username)->find();
            $user || error('用户名不存在!');
            if($user->password !== $password) {
                Cookie::delete('username');
                Cookie::delete('password');
                error('请重新登陆');
            }else{
                //登陆成功
                Session::set(self::LOGIN_NAME,$user->getData());
               return true;
            }
        }
        return false;
    }


    public static function getLoginUser(){
        return Session::get(self::LOGIN_NAME);
    }


    public static function encrypt(string $str):string{
        return md5('ad'.$str.'login');
    }

}